package com.woniu.controller;

import com.alibaba.excel.EasyExcel;

import com.alibaba.fastjson.JSONObject;
import com.woniu.aspect.Log;
import com.woniu.entity.HttpStatus;
import com.woniu.entity.PageData;
import com.woniu.entity.Result;

import com.woniu.entity.dto.QueryUserDTO;

import com.woniu.entity.vo.UserLoginVO;
import com.woniu.pojo.User;
import com.woniu.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaosong
 * @since 2023-04-01
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户管理")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("/all")
    @ApiOperation("查询所有")
    public Result listAll(){
        List<User> users = userService.list();
        return toDataResult(users);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询")
    public Result findById(@PathVariable Integer id){
        User user = userService.getById(id);
        return toDataResult(user);
    }


    @Log(type = "删除")
    @DeleteMapping("/{id}")
    @ApiOperation("删除信息")
    public Result delete(@PathVariable("id") Integer id){
        boolean byId = userService.removeById(id);
        return toDataResult(byId);
    }
    @Log(type = "批量删除")
    @PostMapping("/delete")
    @ApiOperation("批量删除信息")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        boolean byId = userService.removeBatchByIds(ids);
        return toDataResult(byId);
    }

    @PostMapping("/addUpdate")
    @ApiOperation("添加或者修改")
    public Result addOrUpdate(@RequestBody User user){
        boolean flag = false;
        if(StringUtils.isEmpty(user.getId())){
            flag = userService.save(user);
        }else{
            flag = userService.updateById(user);
        }
        //将用户保存的图片储大的redis的set集合中
        String avatar = user.getAvatar();
        String filename = avatar.substring(avatar.lastIndexOf("/") + 1);
        redisTemplate.opsForSet().add("redis_db_upload_image",filename);
        return toResult(flag);
    }
    @Log(type = "添加")
    @PostMapping("/add")
    @ApiOperation("增加成员")
    public Result addUser(@RequestBody User user,HttpServletRequest request){
        boolean b = userService.save(user);
        return new Result(HttpStatus.SUCCESS,"添加成功",b);
    }
    @Log(type = "修改")
    @PostMapping("/update")
    @ApiOperation("修改信息")
    public Result update(@RequestBody User user){
        boolean update = userService.updateUser(user);
        return new Result(HttpStatus.SUCCESS,"修改成功",update);
    }


    @GetMapping("/exist/name")
    @ApiOperation("姓名唯一检验")
    public Result nameExist(@RequestParam String name){
        boolean i=userService.nameExist(name);
        return toDataResult(i);
    }
    @Log(type = "分页查询")
    @PostMapping("/search/{currentPage}/{pageSize}")
    @ApiOperation("分页查询")
    public Result select(
            @PathVariable Integer currentPage,
            @PathVariable Integer pageSize,
            @RequestBody QueryUserDTO queryUserDTO
    ){
        PageData pageData =userService.search(currentPage,pageSize,queryUserDTO);
        return toDataResult(pageData);
    }
    @Log(type = "修改类型")
    @PutMapping("/update/{id}/{userType}")
    @ApiOperation("显示按钮页面")
    public Result update(@PathVariable Integer id,@PathVariable Integer userType){
        System.out.println("userType = " + userType);
        int i=userService.updateType(id,userType);
        if (i>0){
            return toDataResult(i);
        }else {
            return error();
        }
    }
    @Log(type = "导出")
    @ApiOperation("导出数据")
    @PostMapping("/export")
    public void listSearch(@RequestBody(required = false) QueryUserDTO queryUserDTO,
                           HttpServletResponse response) throws IOException {
        PageData pageData =  userService.search(1, 1000, queryUserDTO);
        List<User> users = (List<User>) pageData.getData();
        EasyExcel.write(response.getOutputStream(), User.class).sheet().doWrite(users);
    }

}
